package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase{
	
	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public Set<GroupObject> getGroups() {
		manager.getNavigationHelper().goToGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			//
			title = title.substring("Select (".length(), title.length()-")".length());
			//
			GroupObject group = new GroupObject()
			     .setName(title)
			     .setId(checkbox.getAttribute("value"));
			groups.add(group);
		}
		return groups;
	}
	
	public void createGroup(GroupObject groupObject) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		manager.getNavigationHelper().goToGroupListPage();
	}
	
	public void deleteGroup(int i) {
	    manager.getNavigationHelper().goToGroupListPage();
	    checkGroup(i);
	    submitGroupDeletion();
	    manager.getNavigationHelper().goToGroupListPage();
	}
	
	public void modifyGroup(int i, GroupObject groupObject) {
	    manager.getNavigationHelper().goToGroupListPage();
	    initGroupModification(i);
		fillGroupForm(groupObject);
		submitGroupModification();
	    manager.getNavigationHelper().goToGroupListPage();
	}

	private void submitGroupModification() {
		click(By.name("update"));
	}
	
	private void submitGroupDeletion() {
		 click(By.name("delete"));
	}

	private void initGroupModification(int i) {
		checkGroup(i);
		click(By.name("edit"));
	}

	private void checkGroup(int i) {
		click(By.name("selected[]"));
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	protected void checkCheckbox(int i) {
		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		checkboxes.get(i).click();
	}
	
	public  int getRandomGroupPosition() {
		Set<GroupObject> groups = getGroups();
		float cmp_number = 1.0f;
		Random rand = new Random();
		GroupObject randomGroup = null;
		while(groups.iterator().hasNext()) {
		GroupObject currentGroup = groups.iterator().next();
		if(rand.nextFloat()< cmp_number){
		randomGroup = currentGroup;
		cmp_number = rand.nextFloat();
		}

		int pos = 0;
		for(Object entry:groups){
			if(entry.equals(randomGroup)) return pos;
		}
		}
		return -1;
	}
	
	
}
